<?php

namespace app\home\controller;

// 引入公共控制器
use app\common\controller\Home;

// 引入邮箱发送类
use app\common\library\Email;

class Business extends Home
{
    public function __construct()
    {
        parent::__construct();

        //调用方法判断是否有没有登录
        $this->Islogin();
        
        //保存一个模型
        $this->BusinessModel = model('Business.Business');
        $this->RegionModel = model('Region');
        $this->SubjectModel = model('Subject.Subject');
    }

    // 会员中心
    public function index()
    {
        $business = cookie('business') ? cookie('business') : [];
        //查询用户资料
        $profile = $this->BusinessModel->where(['id' => $business['id']])->find();

        $this->assign([
            'data' => $profile,
        ]);
        return $this->view->fetch();
    }

    // 基本资料
    public function profile()
    {
        $business = cookie('business') ? cookie('business') : [];

        //查询用户资料
        $profile = $this->BusinessModel->where(['id' => $business['id']])->find();

        // 接收post请求
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $nickname = $this->request->param('nickname', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $gender = $this->request->param('gender', '', 'trim');

            // 组装数据
            $data = [
                'id'=>$business['id'],
                'nickname' => $nickname,
                'mobile' => $mobile,
                'gender' => $gender
            ];

            // 是否修改登录密码
            if (!empty($password)) {
                $salt = build_ranstr();
                $password = md5($password . $salt);
                $data['password'] = $password;
                $data['salt'] = $salt;
            }
            // 是否修改邮箱
            if ($email != $profile['email']) {
                $data['email'] = $email;
                // 把认证状态改为0 未认证
                $data['auth'] = 0;
            }

            // 修改省市区
            if ($params['region']) {
                $region = explode('/', $params['region']);

                if (count($region) < 3) {
                    $this->error('请重新选择省市区!');
                }
                $pathcode = $this->RegionModel->where('name', $region[2])->value('parentpath');

                $pathcode = explode(',', $pathcode);

                list($province, $city, $district) = $pathcode;
                $data['province'] = $province;
                $data['city'] = $city;
                $data['district'] = $district;

            }

            // 是否有修改图片
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                $path = '/uploads/';
                $success = UploadFile('avatar', $path);

                // 文件上传失败
                if (!$success['result']) {
                    Notice($success['msg']);
                    exit;
                }
                // 将上传图片数据塞到数组里面
                $data['avatar'] = $success['data'];
            }
    
            // 更新数据库
            $result = $this->BusinessModel->validate('common/business/Business.edit')->isUpdate(true)->save($data);

            // 更新数据库失败
            if ($result === FALSE) {
                if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                    @is_file($profile['avatar']) && @unlink($profile['avatar']);
                }
                // 错误信息可以让模型返回出来
                $this->error($this->BusinessModel->getError());
                exit;
            } else { //更新数据库成功
                if (isset($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                    // //判断新的图片和旧的图片是否一样，如果不一样才删除
                    if ($profile['avatar'] != $data['avatar']) {
                        // 删除旧图片(逻辑短路)
                        @is_file($profile['avatar']) && @unlink($profile['avatar']);
                    }

                }
                // 修改成功,跳转到个人中心界面
                $this->success('修改成功', url('home/business/index'));
                exit;
            }
        }
        // 模板赋值
        $this->assign([
            'data' => $profile,
        ]);
        return $this->view->fetch();
    }
    
    // 邮箱认证
    /**
     * 授权码：MDZSMYRLAMNNSRCM
     * 邮箱：
     */
    public function email()
    {
        // $business = cookie('business') ? cookie('business') : [];

        // //查询用户资料
        // $profile = $this->BusinessModel->where(['id' => $business['id']])->find();
        // // 模板赋值
        // $this->assign([
        //     'data' => $profile,
        // ]);
        if($this->request->isAjax())
        {
            $receiver=isset($this->view->login['email']) ? $this->view->login['email'] : '';
            if(empty($receiver))
            {
                $this->error('邮箱地址为空');
                exit;
            }
            $Ems=model('Ems');
            $where=[
                'event'=>'email',
                'email'=>$receiver,
                'times'=>0
            ];
            $check=$Ems->where($where)->find();
            if($check)
            {
                $this->error('请勿重复发送验证码');
                exit;
            }

            //验证码
            $code = build_ranstr(5);
            // 组装数据
            $data=[
                'event'=>'email',
                'email'=>$receiver,
                'code'=>$code,
                'times'=>0
            ];

            // 开启事务操作
            $Ems->startTrans();
            // 插入
            $res=$Ems->save($data);
            if(!$res)
            {
                $this->error('邮箱验证插入失败');
                exit;
            }

            //实例化邮箱对象
            $email = new Email;
            $html = "<div>您的邮箱认证码为：<b>$code</b></div>";

            // 获取系统配置
            $config=[
                'mail_type' => config('site.mail_type'),
                'mail_smtp_host' => config('site.mail_smtp_host'),
                'mail_smtp_port' => config('site.mail_smtp_port'),
                'mail_smtp_user' => config('site.mail_smtp_user'),
                'mail_smtp_pass' => config('site.mail_smtp_pass'),
                'mail_verify_type' => config('site.mail_verify_type'),
                'mail_from' => config('site.mail_from'),
            ];

            //合并系统配置
            \think\Config::set('site', array_merge(\think\Config::get('site'), $config));

            //发送邮件
            $result = $email->to($receiver)
                ->subject(config('site.name')."邮箱认证")
                ->message($html)
                ->send();
            if($result)
            {
                // 事务提交
                $Ems->commit();
                $this->success('发送验证码成功，请注意查收');
                exit;
            }else
            {
                // 插入邮箱验证回滚
                $Ems->rollback();
                $this->error($email->getError());
                exit;
            }
        }
        return $this->view->fetch();
    }

    // 邮箱验证方法
    public function check()
    {
        if($this->request->isPost())
        {
            $email=isset($this->view->login['email']) ? $this->view->login['email'] : '';
            $code=$this->request->param('code','','trim');

            $where=[
                'event'=>'email',
                'email'=>$email,
                'code'=>$code,
            ];

            // 加载模型
            $EmsModel=model('Ems');
            $BusinessModel=model('Business.Business');

            // 开启事务操作
            $EmsModel->startTrans();
            $BusinessModel->startTrans();

            $row=$EmsModel->where($where)->find();
            if(!$row)
            {
                $this->error('邮箱认证码不正确，请重新输入');
                exit;
            }

            // 更新客户认证状态
            $data=[
                'id'=>$this->view->login['id'],
                'auth'=>'1'
            ];
            $BusinessStatus=$BusinessModel->isUpdate(true)->save($data);
            if($BusinessStatus === FALSE)
            {
                $this->error('邮箱认证失败');
                exit;
            }
            // 删除邮箱验证
            $EmsStatus=$EmsModel->destroy($row['id']);
            if($EmsStatus === FALSE)
            {
                $this->error('删除邮箱认证码失败');
                exit;
            }

            if($BusinessStatus === FALSE || $EmsStatus === FALSE)
            {
                $EmsModel->rollback();
                $BusinessModel->rollback();
                $this->error('认证失败');
                exit;
            }else
            {
                $BusinessModel->commit();
                $EmsModel->commit();
                $this->success('邮箱认证成功',url('home/business/index'));
                exit;
            }
        }
    }

    public function details()
    {
        // application/home/view/index/details.html
        return $this->view->fetch();
    }

    public function order()
    {
        // application/home/view/index/order.html
        return $this->view->fetch();
    }

    // 联系我们
    public function contact()
    {
        $subjectList=$this->SubjectModel->limit(5)->select();
        $this->assign([
            'subjectList'=>$subjectList
        ]);
        // var_dump(collection($subjectList)->toArray());
        // exit;
        return $this->view->fetch();
    }
    // 充值
    public function pay()
    {
        if($this->request->isAjax())
        {
            $info=$this->request->param('info','','trim');
            $money=$this->request->param('money','','trim');
            // $this->success('请求成功',null,floatval($money));
            exit;
            $business=$this->BusinessModel->where('mobile',$info)->find();
            
            if(empty($info))
            {
                $this->error('请输入要充值的账号');
                exit;
            }
            if(!$business)
            {
                $this->error('充值失败，不存在该账户');
                exit;
            }
            $data=[
                'id'=>$business['id'],
                'money'=>$money,
            ];
            // 验证器
            $validate = [
                [
                    'money' => ['require', 'number', '>=:0'],
                ],
                [
                    'money.require' => '余额字段未知',
                    'money.number' => '余额必须得是数字',
                    'money.>=' => '余额必须大于0元',
                ]
            ];
            $result=$this->BusinessModel->validate(...$validate)->isUpdate(true)->save($data);
            if($result)
            {
                $this->success('充值成功');
                exit;
            }else{
                $this->error('充值失败',null,$this->BusinessModel->getError());
                exit;
            }
            // $this->success('请求成功',null,$info);
            // exit;
        }
        return $this->view->fetch();
    }
}